import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { computed, h } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { useUserStore } from '@vben/stores';

import { Modal } from 'ant-design-vue';
import dayjs from 'dayjs';

import { customerListByStaffId } from '#/api/hm/customer';
import { listUserByDeptId } from '#/api/system/user';
import { getDictOptions } from '#/utils/dict';
import { renderDict } from '#/utils/render';
import saleOrderPickUpListModal from '#/views/hm/saleOrder/saleOrderPickUpList-modal.vue';

const userStore = useUserStore();

const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo', 'dept-manage']);
});
// 财务
const isFinance = computed(() => {
  return hasAccessByRoles(['finance']);
});
const isStoreManage = computed(() => {
  return hasAccessByRoles(['shop-owner', 'finance']);
});

// 查询栏Form
export const querySchema: FormSchemaGetter = () => [
  {
    component: 'Input',
    fieldName: 'saleId',
    label: '订单号',
    labelWidth: 90,
  },
  {
    component: 'Select',
    fieldName: 'saleDept',
    // defaultValue: userStore.userInfo?.deptId,
    label: '销售店铺',
    labelWidth: 90,
    dependencies: {
      show: () => isAdmin.value || isFinance.value,
      triggerFields: [''],
    },
  },
  {
    component: 'Select',
    fieldName: 'saleUser',
    label: '销售人员',
    labelWidth: 90,
    dependencies: {
      async componentProps(values) {
        if (values?.saleDept) {
          const ret = await listUserByDeptId(values?.saleDept);
          const transOptions = ret.map((item) => ({
            label: item.userName,
            value: item.userId,
          }));
          const dataSourceOptions = [];
          dataSourceOptions.push(...transOptions);
          return {
            options: dataSourceOptions,
            allowClear: true,
          };
        } else {
          const ret = await listUserByDeptId(userStore.userInfo?.deptId);
          const transOptions = ret.map((item) => ({
            label: item.userName,
            value: item.userId,
          }));
          const dataSourceOptions = [];
          dataSourceOptions.push(...transOptions);
          return {
            options: dataSourceOptions,
            allowClear: true,
          };
        }
      },
      triggerFields: ['saleDept'],
    },
  },
  {
    component: 'Select',
    fieldName: 'customerId',
    label: '服务客户',
    labelWidth: 90,
    componentProps: {
      allowClear: true,
      showSearch: true,
      optionFilterProp: 'label',
    },
    dependencies: {
      async componentProps(values) {
        if (values?.saleUser) {
          const ret = await customerListByStaffId(values.saleUser);
          const transOptions = ret.map((item) => ({
            label: item.customerName,
            value: item.customerId,
          }));
          const dataSourceOptions = [];
          dataSourceOptions.push(...transOptions);
          return {
            options: dataSourceOptions,
          };
        }
        return {};
      },
      triggerFields: ['saleUser'],
    },
  },
  {
    component: 'Select',
    fieldName: 'saleProductId',
    label: '销售产品',
    labelWidth: 90,
  },
  {
    label: '销售时间',
    fieldName: 'saleOrderTime',
    component: 'RangePicker',
    componentProps(model) {
      return {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        onChange: (dates: [string, string]) => {
          if (!dates) {
            model.leaveDays = null; // 假设 leaveDays 是一个与销售时间范围相关的字段
            return;
          }
          const [start, end] = dates;
          const leaveDays = dayjs(end).diff(dayjs(start), 'day') + 1;
          model.leaveDays = leaveDays;
        },
      };
    },
  },
  // 回款时间范围搜索
  {
    label: '回款时间',
    fieldName: 'refundTimeRange', // 这是一个前端临时字段，用于RangePicker
    component: 'RangePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
  },
  {
    component: 'RangeNumber', // 使用新组件
    fieldName: 'refundAmountRange', // 绑定到一个新的字段
    label: '剩余回款额',
    labelWidth: 90,
    componentProps: {
      startPlaceholder: '最小剩余回款额',
      endPlaceholder: '最大剩余回款额',
    },
  },
  // 客户取货剩余量搜索
  {
    component: 'RangeNumber',
    fieldName: 'surplusNumRange',
    label: '剩余提货量',
    labelWidth: 90,
    componentProps: {
      startPlaceholder: '最少数量',
      endPlaceholder: '最多数量',
    },
  },
];

// Table
export const columns: VxeGridProps['columns'] = [
  {
    title: '订单号',
    field: 'saleId',
    width: 170,
    fixed: 'left',
  },
  {
    title: '产品',
    field: 'saleProductName',
    width: 120,
    fixed: 'left',
  },
  {
    title: '客户',
    field: 'customerName',
    width: 80,
    fixed: 'left',
  },
  {
    title: '销售额',
    field: 'saleAmount',
    width: 100,
    cellRender: {
      name: 'CellColorAmount',
      props: { color: 'blue' },
    },
    footerFormatter: ({ itemValue }) => {
      return `${itemValue / 10} 元`;
    },
  },
  {
    title: '销售量',
    field: 'saleNum',
    width: 100,
  },
  {
    title: '销售时间',
    field: 'saleOrderTime',
    width: 110,
  },
  {
    title: '已回款',
    field: 'returnAmount',
    width: 120,
    slots: { default: 'refundAmountHis' },
  },
  {
    title: '未回款',
    field: 'refundSurplusNum',
    width: 100,
    cellRender: { name: 'CellColorAmount', props: { color: 'red' } },
    footerFormatter: ({ itemValue }) => {
      return `${Math.round(itemValue / 10)} 元`;
    },
  },
  {
    title: '已提货',
    field: 'pickUpNum',
    width: 100,
    slots: { default: 'pickUpNumHis' },
  },
  {
    title: '剩余量',
    field: 'surplusNum',
    width: 100,
    cellRender: { name: 'CellColor', props: { color: 'red' } },
  },
  {
    title: '评点',
    field: 'isGift',
    width: 60,
    slots: {
      default: ({ row }) => {
        if (row.isGift) {
          return renderDict(row.isGift, DictEnum.SYS_YES_NO);
        }
        return '-';
      },
    },
  },
  {
    title: '退款状态',
    field: 'refundStatus',
    width: 100,
    slots: {
      default: ({ row }) => {
        if (row.refundStatus) {
          return renderDict(row.refundStatus, DictEnum.ORDER_RERUEN_STATUS);
        }
        return renderDict('0', DictEnum.ORDER_RERUEN_STATUS);
      },
    },
  },
  {
    title: '已退款金额',
    field: 'refundAmount',
    width: 100,
    cellRender: { name: 'CellColorAmount', props: { color: 'red' } },
  },
  {
    title: '退货状态',
    field: 'returnStatus',
    width: 100,
    slots: {
      default: ({ row }) => {
        if (row.returnStatus) {
          return renderDict(
            row.returnStatus,
            DictEnum.ORDER_RERUEN_PRODUCT_STATUS,
          );
        }
        return renderDict('0', DictEnum.ORDER_RERUEN_PRODUCT_STATUS);
      },
    },
  },
  {
    title: '已退货数量',
    field: 'returnTotalNum',
    width: 100,
    cellRender: { name: 'CellColor', props: { color: 'red' } },
  },
  {
    title: '评点商品',
    field: 'giftList',
    width: 500,
    cellRender: {
      name: 'GiftTagsRenderer',
      props: {
        // 133 200 148
        tagColor: 'rgb(133 200 148)', // 可配置化参数
        onTagClick: (gift: any) => {
          showGiftDetailModal(gift);
        },
      },
    },
  },
  {
    title: '店铺',
    field: 'saleDeptName',
    width: 100,
  },
  {
    title: '销售员',
    field: 'saleUserName',
    width: 100,
    fixed: 'right',
  },
  {
    field: 'action',
    fixed: 'right',
    slots: { default: 'action' },
    title: '操作',
    width: 355,
  },
];

/**
 * @description: 动态生成评点产品和数量的表单项
 * @param count - 需要生成的对数
 * @returns FormSchema[]
 */
const createGiftItemSchemas = (count: number): FormSchema[] => {
  const schemas: any[] = [];
  for (let i = 1; i <= count; i++) {
    schemas.push(
      {
        label: `评点产品${i}`,
        fieldName: `giftProductId${i}`,
        component: 'Select',
        rules: i === 1 ? 'required' : undefined, // 仅第一项为必填
        componentProps: {
          placeholder: `请选择评点产品 ${i}`,
        },
        dependencies: {
          show: (values) => values.isGift === 'Y',
          triggerFields: ['isGift'],
        },
      },
      {
        label: `评点数量${i}`,
        fieldName: `giftNum${i}`,
        component: 'InputNumber',
        rules: i === 1 ? 'required' : undefined, // 仅第一项为必填
        componentProps: {
          min: 1,
          style: { width: '100%' },
          precision: 2,
        },
        dependencies: {
          show: (values) => values.isGift === 'Y',
          triggerFields: ['isGift'],
        },
      },
    );
  }
  return schemas;
};

// 弹窗Form
export const modalSchema: FormSchemaGetter = () => [
  {
    label: '销售id',
    fieldName: 'saleId',
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    label: '销售产品',
    fieldName: 'saleProductId',
    component: 'Select',
    rules: 'required',
    labelWidth: 100,
    dependencies: {
      triggerFields: ['saleId'],
    },
  },
  {
    label: '销售数量',
    fieldName: 'saleNum',
    component: 'InputNumber',
    rules: 'required',
    labelWidth: 100,
    componentProps: {
      precision: 2,
      min: 0,
    },
    dependencies: {
      triggerFields: ['saleId'],
    },
  },
  {
    label: '总金额',
    fieldName: 'saleAmount',
    component: 'InputNumber',
    rules: 'required',
    componentProps: {
      precision: 2,
      min: 0,
    },
    labelWidth: 100,
    dependencies: {
      triggerFields: ['saleId'],
    },
    renderComponentContent: () => ({
      prefix: () => '￥',
    }),
  },
  {
    label: '销售店铺',
    fieldName: 'saleDept',
    component: 'Select',
    rules: 'required',
    // 默认当前登录人所在店铺
    defaultValue: userStore.userInfo?.deptId,
    labelWidth: 100,
    dependencies: {
      show: () => isAdmin.value,
      triggerFields: ['saleId'],
    },
  },
  {
    label: '销售人员',
    fieldName: 'saleUser',
    component: 'Select',
    rules: 'required',
    componentProps: {
      showSearch: true,
      optionFilterProp: 'label',
    },
    labelWidth: 100,
    dependencies: {
      async componentProps(values) {
        const ret = await listUserByDeptId(values?.saleDept);
        const transOptions = ret.map((item) => ({
          label: item.userName,
          value: item.userId,
        }));
        const dataSourceOptions = [];
        dataSourceOptions.push(...transOptions);
        if (values?.saleDept && !values?.saleId) {
          values.saleUser = undefined;

          // 默认当前登录人Id
          const filteredItems = transOptions
            .filter((item) => Number(item.value) === userStore.userInfo?.userId)
            .map((item) => item.value);

          values.saleUser =
            filteredItems.length > 0 ? filteredItems[0] : undefined;
          return { options: dataSourceOptions };
        }
        return {
          options: dataSourceOptions,
        };
      },
      show: () => isAdmin.value || isStoreManage.value,

      triggerFields: ['saleDept', 'saleId'],
    },
  },
  {
    label: '服务客户',
    fieldName: 'customerId',
    component: 'Select',
    rules: 'required',
    componentProps: {
      allowClear: true,
      showSearch: true,
      optionFilterProp: 'label',
    },
    dependencies: {
      async componentProps(values) {
        if (isAdmin.value || isStoreManage.value) {
          // 管理员
          if (values?.saleUser) {
            const ret = await customerListByStaffId(values.saleUser);
            const transOptions = ret.map((item) => ({
              label: item.customerName,
              value: item.customerId,
            }));
            const dataSourceOptions = [];
            dataSourceOptions.push(...transOptions);
            return {
              options: dataSourceOptions,
            };
          }
        } else {
          const userId = userStore.userInfo?.userId;
          const ret = await customerListByStaffId(userId);
          const transOptions = ret.map((item) => ({
            label: item.customerName,
            value: item.customerId,
          }));
          const dataSourceOptions = [];
          dataSourceOptions.push(...transOptions);
          return {
            options: dataSourceOptions,
          };
        }
        return {};
      },

      triggerFields: ['saleUser', 'saleId'],
    },
  },
  {
    label: '销售时间',
    fieldName: 'saleOrderTime',
    component: 'DatePicker',
    componentProps: {
      showTime: true,
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      disabledDate: (current: dayjs.Dayjs) => {
        return current && current.isAfter(dayjs().endOf('day'));
      },
    },
    rules: 'required',
    dependencies: {
      triggerFields: ['saleId'],
    },
  },
  {
    label: '是否评点',
    fieldName: 'isGift',
    component: 'RadioGroup',
    rules: 'required',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_YES_NO),
    },
    defaultValue: 'N',
    dependencies: {
      triggerFields: ['saleId'],
    },
  },
  // --- 此处为动态生成的评点项目 ---
  ...createGiftItemSchemas(5),
  {
    label: '状态',
    fieldName: 'status',
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
    },
    rules: 'selectRequired',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
  },
  {
    label: '备注',
    fieldName: 'remark',
    component: 'Input',
    formItemClass: 'col-span-2',
    // rules: 'required',
  },
];

// 弹窗详情展示方法
const showGiftDetailModal = (gift: any) => {
  console.log('gift:', gift);
  Modal.info({
    title: `${gift.giftProductName} 详情`,
    width: 600,
    maskClosable: true,
    content: h('div', { class: 'gift-modal-content' }, [
      h('p', { class: 'gift-field' }, [
        h('span', { class: 'label' }, '商品ID: '),
        h('code', gift.giftProductId),
      ]),
      h('p', { class: 'gift-field' }, [
        h('span', { class: 'label' }, '总数量: '),
        h('span', { style: 'color: #1890ff;' }, gift.giftNum),
      ]),
      h('p', { class: 'gift-field' }, [
        h('span', { class: 'label' }, '退货数量: '),
        h('span', { style: 'color: #ff4d4f;' }, gift.giftRefundableNum),
      ]),
      h('p', { class: 'gift-field' }, [
        h('span', { class: 'label' }, '已提货: '),
        h(
          'a',
          {
            style: 'color: #52c41a; cursor: pointer;',
            onClick: (e) => {
              e.preventDefault();
              openPickUpRecords(gift); // ✅ 传递整个对象
            },
          },
          gift.giftUsedNum,
        ),
      ]),
      ,
      h('p', { class: 'gift-field' }, [
        h('span', { class: 'label' }, '剩余量: '),
        h(
          'span',
          { style: 'color: #ff4d4f;' },
          gift.giftNum - gift.giftUsedNum === 0
            ? 0
            : gift.giftNum - gift.giftRefundableNum - gift.giftUsedNum,
        ),
      ]),
      h('p', { class: 'gift-field' }, [
        h('span', { class: 'label' }, '状态: '),
        h(
          'span',
          {
            style: `color: ${gift.giftStatus === 0 ? '#52c41a' : '#ff4d4f'};`,
          },
          gift.giftStatus === 0 ? '正常' : '已失效',
        ),
      ]),
      <SaleOrderPickUpListModal />,
    ]),
  });
};
// 初始化提货记录模态框
// 模态框初始化（补充关键配置）
const [SaleOrderPickUpListModal, pickUpModalListApi] = useVbenModal({
  connectedComponent: saleOrderPickUpListModal,
});
// 打开提货记录弹窗
const openPickUpRecords = (gift: any) => {
  if (!gift?.giftId) return;
  // 根据图片数据结构设置参数
  console.log('gift:', gift);
  pickUpModalListApi.setData({
    productId: gift.giftProductId, // 销售产品id
    pickUpType: 'pickUpNumHisZP',
    saleOrderId: gift.saleId,
  });

  pickUpModalListApi.open();
};
